package com.zwy.springecho;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class RequestLoggingAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    // 定义切点，拦截所有带有@GetMapping、@PostMapping和@RequestMapping注解的方法
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
              "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
              "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void requestMappingMethods() {}

    @Before("requestMappingMethods()")
    public void logRequest(JoinPoint joinPoint) {
        // 获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        // 打印URL和请求方式
        logger.info("URL: {}", request.getRequestURL());
        logger.info("HTTP Method: {}", request.getMethod());
        logger.info("参数: {}", joinPoint.getArgs());
        // 打印请求参数
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            logger.info("Parameter: {} = {}", paramName, paramValue);
        }
        // 如果不是multipart请求，打印请求体
        if (!(request instanceof MultipartHttpServletRequest)) {
            logger.info("Request Body: {}", RequestUtils.getCachedRequestBody(request));
        }
    }
}
